package com.rritw.webtools.action.tool;

import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;

import com.rritw.webtools.action.IpsAction;
import com.rritw.webtools.util.StringUtil;

@Controller
@Scope("prototype")
public class UrlEncodeDecodeAction extends IpsAction {

    private static final long   serialVersionUID = -9054900985715655779L;
    private static final Logger log              = Logger.getLogger(UrlEncodeDecodeAction.class);
    private String              content;
    private String              action;
    private String              charset;

    private String              contentResult;

    public String index() {
        super.init();
        return SUCCESS;
    }

    public String create() {
        try {
            super.init();
            if (StringUtil.isEmpty(content)) {
                return ERROR;
            }
            if (StringUtil.isEmpty(charset)) {
                return ERROR;
            }
            if ("encode".equals(action)) {
                contentResult = URLEncoder.encode(content, charset);
            } else {
                contentResult = URLDecoder.decode(content, charset);
            }
            if (!StringUtil.isEmpty(content)) {
                content = HtmlUtils.htmlEscape(content);
            }
            if (!StringUtil.isEmpty(contentResult)) {
                contentResult = HtmlUtils.htmlEscape(contentResult);
            }
        } catch (Exception e) {
            log.error(this.getClass().getName() + ":" + e.getMessage(), e);
        }
        return SUCCESS;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContentResult() {
        return contentResult;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }
}
